package org.wiztools.commons.feed;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.parser.stax.FOMUnsupportedTextTypeException;
import org.apache.log4j.Logger;

public class AbderaFeedExecuter extends AbstractFeedExecuter {

    private static final Logger LOG = Logger.getLogger(AbderaFeedExecuter.class);

    private static final String OSURI = "http://a9.com/-/spec/opensearch/1.1/";
    private static final String OPENSEARCH_NS = "opensearch";

    private static final QName TOTALRESULTS = new QName(
            OSURI, "totalResults", OPENSEARCH_NS);
    private static final QName STARTINDEX = new QName(
            OSURI, "startIndex", OPENSEARCH_NS);
    private static final QName ITEMSPERPAGE = new QName(
            OSURI, "itemsPerPage", OPENSEARCH_NS);

    @Override
    public Feed getFeed(URL url) throws FeedException, IOException {
        Abdera abdera = new Abdera();
        Parser parser = abdera.getParser();
        Document<org.apache.abdera.model.Feed> document = parser.parse(
                HttpUtil.getConnectionStream(url, options));
        org.apache.abdera.model.Feed feed = document.getRoot();

        Feed out = new Feed();
        out.setUrl(url);
        out.setTitle(feed.getTitle());
        out.setDescription(feed.getSubtitle());

        // Add OpenSearch Extension
        try{
            if(feed.getExtension(TOTALRESULTS) != null
                    && feed.getExtension(STARTINDEX) != null){
                out.addExtension(OpenSearchExtension.totalResults,
                        Integer.parseInt(feed.getExtension(TOTALRESULTS).getText()));
                out.addExtension(OpenSearchExtension.startIndex,
                        Integer.parseInt(feed.getExtension(STARTINDEX).getText()));
                if(feed.getExtension(ITEMSPERPAGE) != null) {
                    out.addExtension(OpenSearchExtension.itemsPerPage,
                    Integer.parseInt(feed.getExtension(ITEMSPERPAGE).getText()));
                }
            }
        }
        catch(FOMUnsupportedTextTypeException ex){
            LOG.info("OpenSearch not supported in current Feed!");
        }

        // Get the entries
        List<FeedEntry> outEntries = new ArrayList<FeedEntry>();
        List<Entry> entries = feed.getEntries();
        LOG.info("Size of entries: " + entries.size());
        for(Entry entry: entries){
            try{
                FeedEntry outEntry = new FeedEntry();
                //entry.getLink("").getHref().toURL();
                outEntry.setUrl(entry.getAlternateLink().getHref().toURL());
                outEntry.setTitle(entry.getTitle());
                LOG.info("Title: " + entry.getTitle());
                outEntry.setSummary(entry.getSummary());
                outEntry.setContent(entry.getContent());
                outEntry.setPublishedDate(entry.getPublished());
                outEntry.setUpdatedDate(entry.getUpdated());

                // Add to list:
                outEntries.add(outEntry);
            }
            catch(URISyntaxException ex){
                throw new FeedException(ex);
            }
        }
        out.setEntries(outEntries);
        return out;
    }
}
